/**
 * @(#)AnalyzeProjectAction.java, 2008-4-30.
 * Copyright 2008  Program Analysis Research Group(PARG),Institute of Software, Peking University.
 * All rights reserved.
 */
package edu.pku.sei.pgie.ui.actions;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import edu.pku.sei.pgie.Activator;
import edu.pku.sei.pgie.analyzer.core.Analyzer;
import edu.pku.sei.pgie.analyzer.core.Context;

/**
 * @author HeLi
 */
public class AnalyzeProjectAction implements IObjectActionDelegate {
	ISelection selection;

	Shell shell;

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.shell = targetPart.getSite().getShell();
	}

	public void run(IAction action) {
		if (!(this.selection instanceof IStructuredSelection))
			return;

		IStructuredSelection structureSelection = (IStructuredSelection) this.selection;
		final IJavaProject javaProject = (IJavaProject) structureSelection
				.getFirstElement();

		Job analyzeJob = new Job("Analyze Source Code") {
			protected IStatus run(IProgressMonitor monitor) {
				Context context = null;
				try {
					IPreferenceStore store = Activator.getDefault()
							.getPreferenceStore();
					context = new Context(store);
					context.setJavaProject(javaProject);

					Analyzer analyzer = new Analyzer(context);
					analyzer.anlayze(monitor);

					return Status.OK_STATUS;
				} catch (Exception e) {
					return new Status(Status.ERROR, Activator.PLUGINID, 0,
							"Exception During Analyze", e);
				} finally {
					if (context != null) {
						context.dispose();
					}
				}
			}
		};
		analyzeJob.setUser(true);
		analyzeJob.schedule();
	}

	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = selection;
	}

}
